<template>
	<view class="Map">
		<view class="search">
			<u--input class="input" placeholder="请输入内容" border="surround" clearable v-model="keyword"></u--input>
			<u-button class="btn" type="primary" text="查找" @click="search"></u-button>
		</view>
		<div id="tmap" class="tmap"></div>
	</view>
</template>

<script>
	import {
		loadTMap
	} from '@/utils/tmap.js'
	import {
		getSearchPlace
	} from "@/api/api.js"
	export default {
		async onLoad() {
			//获取用户位置
			function isWeChat() {
				return /micromessenger/i.test(navigator && navigator.userAgent)
			}
			if (isWeChat()) {
				alert('当前在微信中，定位受限，请点击右上角“…”，选择“在浏览器中打开”，即可精准定位。')
			}
			// 1. 先尝试 uni.getLocation
			try {
				const res = await uni.getLocation({
					type: 'gcj02', // 返回国测局坐标系（高德、腾讯地图适用）
					// type: 'wgs84', // 返回 GPS 坐标系（百度地图适用
				})
				console.log('APP 定位成功:', res);
				this.latitude = res.latitude;
				this.longitude = res.longitude;
			} catch (e) {
				// 2. 降级：使用浏览器原生 API
				if (navigator && navigator.geolocation) {
					try {
						// AMap.plugin('AMap.Geolocation', () => {
						// 	const geolocation = new AMap.Geolocation({
						// 		enableHighAccuracy: true,
						// 		timeout: 10000,
						// 		position: 'rt', // 获取坐标
						// 		extensions: 'all' // 返回详细信息（包括城市）
						// 	})

						// 	geolocation.getCurrentPosition((status, result) => {
						// 		if (status === 'complete') {
						// 			console.log('高德SDK精准定位成功:', result);
						// 			const {
						// 				lng,
						// 				lat
						// 			} = result.position
						// 			this.latitude = lat;
						// 			this.longitude = lng;
						// 		}
						// 	})
						// })
						const position = navigator.geolocation.getCurrentPosition(
							(position) => {
								const res = position.coords
								console.log('H5/Web定位成功:', res)
								this.latitude = res.latitude;
								this.longitude = res.longitude;
							},
							(err) => {}, {
								timeout: 10000,
								enableHighAccuracy: true
							});
					} catch (err) {}
				}
			}
		},
		data() {
			return {
				map: null,
				latitude: 39.9, //当前纬度
				longitude: 116.4, //当前经度
				keyword: '', //搜索值
				markers: [], //所有标记
				canvasGroundLayer: '', //地面图层
				range: 5000 //搜索范围
			}
		},
		mounted() {
			setTimeout(async () => {
				try {
					await loadTMap('OYLBZ-V52WL-ZOZP7-EL2WI-WCKGZ-B5BQG'); // 替换为你的 Key
					this.initMap();
					const position = new TMap.LatLng(this.latitude, this.longitude)
					this.addLayer(this.latitude, this.longitude, this.range)
					const marker = new TMap.MultiMarker({
						map: this.map, // 绑定到地图
						styles: {
							"myStyle": new TMap.MarkerStyle({
								width: 32,
								height: 32,
								src: '/static/logo.png', //图片路径
								"anchor": { //焦点在图片中的像素位置
									x: 16,
									y: 16
								}
							})
						},
						geometries: [{
							// id: "1", //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
							styleId: 'myStyle', //指定样式id
							position, //点标记坐标位置
						}]
					});
					// 信息窗口
					const infoWindow = new TMap.InfoWindow({
						map: this.map,
						content: `<div>当前位置</div>`,
						position,
					})
					marker.on('click', (e) => {
						infoWindow.open();
					})
					// this.addCircle(this.latitude, this.longitude, 1000)
				} catch (err) {
					console.log('errerr', err);
				}
			}, 500)
		},
		methods: {
			// 初始化地图
			initMap() {
				const center = new TMap.LatLng(this.latitude, this.longitude)
				this.map = new TMap.Map(document.getElementById('tmap'), {
					center: center, // 中心点
					zoom: 12, // 缩放级别
					mapStyleId: 'style1', // 可选：地图样式（默认标准蓝）
					draggable: true, // 允许拖拽（默认 true）
					scrollable: true, // 允许滚轮缩放（新版叫 scrollable）
					keyboard: true, // 允许键盘操作
				})
				let control = TMap.constants.DEFAULT_CONTROL_ID.FLOOR;
				this.map.removeControl('zoom') //移除缩放控件
				this.map.removeControl('scale') //移除比例尺控件
				this.map.removeControl('rotation') //移除旋转控件
			},
			async search() {
				this.markers.setGeometries && this.markers.setGeometries([]) //清除标记
				this.canvasGroundLayer && this.canvasGroundLayer.setMap(null); //清除地面图层
				this.addLayer(this.latitude, this.longitude, this.range)
				const keyword = this.keyword.trim()
				if (!keyword) return
				const {
					data
				} = await getSearchPlace({
					keyword,
					latitude: this.latitude,
					longitude: this.longitude,
					range: this.range
				})
				console.log(data);
				const {
					lng,
					lat
				} = data[0].location
				// 移动地图
				this.map.setCenter(new TMap.LatLng(lat, lng))
				this.map.setZoom(12)
				// 添加标记
				this.markers = new TMap.MultiMarker({
					map: this.map,
					geometries: data.map((v, i) => ({
						id: v.id,
						position: new TMap.LatLng(v.location.lat, v.location.lng),
						properties: {
							title: v.title, //传入地址，后面导航用
							city: v.ad_info.city //传入城市，后面导航用
						}
					}))
				})
				const position = new TMap.LatLng(this.latitude, this.longitude)
				const infoWindow = new TMap.InfoWindow({
					map: this.map,
					position,
					offset: {
						x: 0,
						y: -32
					} //设置信息窗相对position偏移像素，为了使其显示在Marker的上方
				})
				infoWindow.close()
				this.markers.on('click', (e) => {
					const markInfo = e.geometry.properties;
					infoWindow.open();
					infoWindow.setPosition(e.geometry.position); //设置信息窗位置
					const contents =
						`<div>${markInfo.title}<button onclick="window.open('https://apis.map.qq.com/uri/v1/search?keyword=${markInfo.title}&region=${markInfo.city}&referer=OYLBZ-V52WL-ZOZP7-EL2WI-WCKGZ-B5BQG',
					'_blank')">查看</button></div>`
					infoWindow.setContent(contents)
				})
			},
			// 添加地面图层
			addLayer(lat, lng, radius) {
				var canvas = document.createElement('canvas');
				canvas.width = 500;
				canvas.height = 500;
				var ctx = canvas.getContext("2d");
				// 画布的宽高
				var cWidth = canvas.width;
				var cHeight = canvas.height;
				// 中心点
				var centerX = canvas.width / 2;
				var centerY = canvas.height / 2;
				var drawCircle = function(r, lineWidth = 1, color = "rgba(123,153,255,0.5)") {
					ctx.beginPath();
					ctx.setLineDash([]);
					ctx.arc(centerX, centerY, r, 0, 2 * Math.PI);
					ctx.lineWidth = lineWidth;
					ctx.strokeStyle = color;
					ctx.fillStyle = "rgba(42,91,255,.1)";
					ctx.stroke();
					ctx.fill();
				};
				drawCircle(500 / 2 - 1, 0.5); //半径，边框宽度
				const lstOffset = radius / 111000;
				const lngOffset = radius / (111000 * Math.cos(lat * Math.PI / 180));
				const imageSW = new TMap.LatLng(lat - lstOffset, lng - lngOffset);
				const imageNE = new TMap.LatLng(lat + lstOffset, lng + lngOffset);
				const canvasLatLngBounds = new TMap.LatLngBounds(imageSW, imageNE);
				this.canvasGroundLayer = new TMap.CanvasGroundLayer({
					bounds: canvasLatLngBounds,
					canvas: canvas,
					map: this.map,
				})
			},
			// 添加覆盖物
			addCircle(lat, lng) {
				//自定义DOM覆盖物 - 继承DOMOverlay
				var mydom;

				function myInfoWindow(options) {
					TMap.DOMOverlay.call(this, options);
				}
				myInfoWindow.prototype = new TMap.DOMOverlay();
				// 初始化
				myInfoWindow.prototype.onInit = function(options) {
					this.position = options.position;
					this.content = options.content;
				};
				myInfoWindow.prototype.createDOM = function() {
					mydom = document.createElement("div");
					mydom.style.cssText =
						`height:100px;width:100px;padding:5px;background:rgb(245,249,255,.8);border:#ccc solid 1px;border-radius:50%;line-height:15px;font-size:12px;position:absolute;top:0px;left:0px;`;
					mydom.innerHTML = this.content;
					return mydom;
				};
				// 更新DOM元素，在地图移动/缩放后执行
				myInfoWindow.prototype.updateDOM = function() {
					// 经纬度坐标转容器像素坐标
					let pixel = this.map.projectToContainer(this.position);
					let left = pixel.getX() - this.dom.clientWidth / 2 + 'px'; //水平居中
					let top = pixel.getY() - this.dom.clientHeight / 2 + 'px';
					//将平面坐标转为三维空间坐标
					this.dom.style.transform = `translate3d(${left}, ${top}, 0px)`;
				};
				var myIW = new myInfoWindow({
					map: this.map,
					position: new TMap.LatLng(lat, lng),
					content: ""
				})
			}
		},
	}
</script>
<style lang="scss">
	.Map {}

	.tmap {
		width: 100%;
		height: 100vh;
	}

	.search {
		position: fixed;
		padding: 20rpx;
		top: 0;
		width: calc(100% - 40rpx);
		display: flex;
		justify-content: space-between;
		z-index: 9999;
		background-color: #fff;

		.input {
			background-color: #eee;
		}

		.btn {
			width: 160rpx;
			margin-left: 20rpx;
		}
	}
</style>